package guitar

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"go-weixin/app/guitar/api/internal/svc"
	"go-weixin/app/guitar/api/internal/types"
	"go-weixin/common/utils"

	"github.com/signintech/gopdf"
	"github.com/zeromicro/go-zero/core/logx"
)

type GuitarPdfLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	ut     *utils.Utils
}

func NewGuitarPdfLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GuitarPdfLogic {
	return &GuitarPdfLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		ut:     utils.UT,
	}
}

func (l *GuitarPdfLogic) GuitarPdf(req *types.GuitarPdfReq, w http.ResponseWriter) (resp *types.GuitarPdfResp, err error) {
	// 1. 初始化pdf参数
	pdf := gopdf.GoPdf{}
	pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
	pageHeight := gopdf.PageSizeA4.H
	pageWeight := gopdf.PageSizeA4.W
	borderTop := 50.0
	borderBottom := 50.0
	currentTime := time.Now().Format("2006-01-02 15:04:05")

	// 初始化行高,列宽
	rowHeight := 20.0
	columnWidths := []float64{50, 50, 50, 50, 50, 50, 50, 50}

	// 2.字体配置
	ariblkFont := l.ut.ObjPath.GetStaticPwd([]string{"ariblk.ttf"})
	err = pdf.AddTTFFont("ariblk", ariblkFont)
	if err != nil {
		logx.Error(err.Error())
		return nil, err
	}

	err = pdf.SetFont("ariblk", "", 10)
	if err != nil {
		logx.Error(err.Error())
		return nil, err
	}

	// 3.页眉
	pdf.AddHeader(func() {
		pdf.SetXY(pageWeight/2, borderTop/2)
		// 画图
		pdf.Image(l.ut.ObjPath.GetStaticPwd([]string{"aliyun.PNG"}), pageHeight/4, borderTop/2, &gopdf.Rect{W: 30, H: 20})
		pdf.Cell(nil, "----header---")
	})

	// 4.页尾
	pdf.AddFooter(func() {
		pdf.SetXY(pageWeight/2, pageHeight-(borderBottom/2))
		pdf.Cell(nil, "----footer----")
		pdf.SetX(pageWeight / 4)
		pdf.Cell(nil, currentTime)
	})

	pdf.AddPage()
	// 5.表格绘制
	var rowCount int
	pdf.SetY(borderTop)
	for i := 0; i < 50; i++ {
		// 获取当前所在位置高度
		nowHeight := pdf.GetY()

		// 获取下一行的高度
		nextRowHeight := nowHeight + rowHeight // 假设下一行高度比当前行高度多2mm

		if nextRowHeight > (pageHeight - float64(borderBottom)) {
			// 如果下一行的高度超过了当前页面的剩余空间，则添加新页面
			pdf.AddPage()
			pdf.SetY(borderTop)
		}

		// 在新的一行开始
		pdf.Br(rowHeight)
		// 在每一列添加单元格
		for _, width := range columnWidths {
			// 添加单元格
			pdf.CellWithOption(&gopdf.Rect{
				W: width,
				H: rowHeight,
			}, fmt.Sprintf("%d,%d", i+1, rowCount), gopdf.CellOption{Align: gopdf.Center | gopdf.Middle})
		}
	}

	// 写入http
	n, err := pdf.WriteTo(w)
	logx.Error(n)
	if err != nil {
		return nil, err
	}
	return
}
